package com.ys.service.finance.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.dto.AddDto;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.finance.TcwExpenseAllocationByManage;
import com.ys.entity.finance.TcwExpenseAllocationByManageItem;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.finance.TcwAccountCountForCompanyMapper;
import com.ys.mapper.finance.TcwExpenseAllocationByManageItemMapper;
import com.ys.mapper.finance.TcwExpenseAllocationByManageMapper;
import com.ys.mapper.finance.TcwOperateFrozenRunningMapper;
import com.ys.mapper.hr.HrMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.finance.TcwExpenseAllocationByManageService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 *
 */
@Service("tcwExpenseAllocationByManageService")
public class TcwExpenseAllocationByManageServiceImpl implements TcwExpenseAllocationByManageService {
	private static final Logger logger = LoggerFactory.getLogger(TcwExpenseAllocationByManageServiceImpl.class);
	@Autowired
	private TcwExpenseAllocationByManageMapper tcwExpenseAllocationByManageMapper;

	@Autowired
	private TcwExpenseAllocationByManageItemMapper tcwExpenseAllocationByManageItemMapper;

	@Autowired
	private TcwAccountCountForCompanyMapper tcwAccountCountForCompanyMapper;

	@Autowired
	private TcwOperateFrozenRunningMapper tcwOperateFrozenRunningMapper;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private HrMapper hrMapper;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private CommonApiService<TcwExpenseAllocationByManage> commonApiService;

	@Autowired
	private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;



	//是否验证
	private Predicate<Map<String, Object>> isCheck = e -> e.get("isCheck").toString().equals("1");

	/*
	 * 新增
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R add(Map<String, Object> params,long menuId) throws Exception {
		//验证
		String msg = yzMsg(params,menuId);
		if (msg != null){
			return R.error(msg);
		}
		TcwExpenseAllocationByManage tcwExpenseAllocationByManage = JSON.parseObject(JSON.toJSONString(params), TcwExpenseAllocationByManage.class);
		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();


		String errMsgBySub = "";
		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			for (int i = 0; i < subData.size(); i++) {
				JSONObject jSONObject = subData.getJSONObject(i);
				Map<String, Object> paramsNew = new HashMap<>();
				for (String key : jSONObject.keySet()) {
					paramsNew.put(key,jSONObject.get(key));
				}
				if(isCheck.test(params)){
					//税号验证
					if(checkUtil.isNotNullByObject(paramsNew.get("vgsbmout")) && checkUtil.isNotNullByObject(paramsNew.get("vgsbmin"))){
						ThrOperateCompanyApply outCompany = new ThrOperateCompanyApply().setVgsbm(paramsNew.get("vgsbmout").toString()).queryFirst();
						ThrOperateCompanyApply inCompany = new ThrOperateCompanyApply().setVgsbm(paramsNew.get("vgsbmin").toString()).queryFirst();
						if(!outCompany.getVgsSh().equals(inCompany.getVgsSh())){
							errMsgBySub += "第"+(i+1)+"行信息，不同公司实体无法划拨";
						}
					}

				}
//				paramsNew.put("pid",tcwExpenseAllocationByManage.getId());//单号
				paramsNewByItem.add(paramsNew);
			}

		}else {
			return R.error("详情信息为空！");
		}

//		//负载判断
//		if(isCheck.test(params)){
//			errMsgBySub = amountCheck(paramsNewByItem);
//		}

		if (errMsgBySub != null && !"".equals(errMsgBySub)){
			return R.error(errMsgBySub);
		}

		String wrongmassage=null;
//		for (int i = 0; i < paramsNewByItem.size(); i++){
//			Map<String, Object> item=paramsNewByItem.get(i);
//			String out=item.get("operationsAttributeout").toString();
//			String in=item.get("operationsAttributein").toString();
//			if(!out.equals(in)){
//				wrongmassage="划出与划入运营属性要相同！";
//			}
//		}
		if(wrongmassage !=null){
			return R.error(wrongmassage);
		}
		
		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
		if(tsUserChange!=null){
			tcwExpenseAllocationByManage.setCreateChangeId(tsUserChange.getId());//制单人变更信息
		}else {
			return R.error("未查询到制单人信息！");
		}

		tcwExpenseAllocationByManage.setStatus(1);
		tcwExpenseAllocationByManage.setEffectStock(FlowEnum.EffectStock.NOT_EFFECT.value);

		TcwExpenseAllocationByManage oldEntity = new TcwExpenseAllocationByManage().setBid(tcwExpenseAllocationByManage.getBid()).queryFirst();
		if(oldEntity!=null && oldEntity.getId()!=null){
			tcwExpenseAllocationByManage.setId(oldEntity.getId());
			tcwExpenseAllocationByManageMapper.update(tcwExpenseAllocationByManage);
		}else {
			tcwExpenseAllocationByManageMapper.insert(tcwExpenseAllocationByManage);
		}
		//tcwExpenseAllocationByManageMapper.insert(tcwExpenseAllocationByManage);


		// 删除子数据
		List<TcwExpenseAllocationByManageItem> listDetail = new TcwExpenseAllocationByManageItem().setPbid(tcwExpenseAllocationByManage.getBid()).queryList();
		if(listDetail!=null &&listDetail.size()>0){
			for(TcwExpenseAllocationByManageItem detail : listDetail) {
				tcwExpenseAllocationByManageItemMapper.deleteTrue(detail.getId());
			}
		}

		for(Map<String, Object> item:paramsNewByItem){
			if(item.get("premark")!=null){
				item.put("remark",item.get("premark"));
			}
			TcwExpenseAllocationByManageItem tcwExpenseAllocationByManageItem = JSON.parseObject(JSON.toJSONString(item), TcwExpenseAllocationByManageItem.class);
			tcwExpenseAllocationByManageItem.setStatus(1);
			tcwExpenseAllocationByManageItem.setPbid(tcwExpenseAllocationByManage.getBid());

			tcwExpenseAllocationByManageItemMapper.insert(tcwExpenseAllocationByManageItem);
		}
		YsMenu ysMenu = new YsMenu().setId(MenuId.TCW_ExpenseAllocation_ByManage).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, tcwExpenseAllocationByManage.getBid(), createUserId);
		}
		return R.ok(AddDto.gotoEdit("/web/finance/tcwExpenseAllocationByManage/toEdit?bid=" + tcwExpenseAllocationByManage.getBid()));
	}




	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R edit(String bid,Map<String, Object> params,long menuId) throws Exception {
		Integer stateFlow = yspTaskService.flowState(bid);
		if (stateFlow != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("非制单中数据，无法修改");
		}
		// 验证是否制单人
		YsProcInst entity = new YsProcInst().setBid(bid).queryFirst();
		if (!entity.getCreateUserId().equals(ShiroUtils.getUserId())) {
			return R.error("非制单人无法修改");
		}

		//验证
		String msg = yzMsg(params,menuId);
		if (msg != null){
			return R.error(msg);
		}

		TcwExpenseAllocationByManage tcwExpenseAllocationByManage = JSON.parseObject(JSON.toJSONString(params), TcwExpenseAllocationByManage.class);

		tcwExpenseAllocationByManageMapper.update(tcwExpenseAllocationByManage);
		//验证详情信息
		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
		String errMsgBySub = "";

		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			for (int i = 0; i < subData.size(); i++) {
				JSONObject jSONObject = subData.getJSONObject(i);
				Map<String, Object> paramsNew = new HashMap<>();
				for (String key : jSONObject.keySet()) {
					paramsNew.put(key,jSONObject.get(key));
				}

				//税号验证
				if(checkUtil.isNotNullByObject(paramsNew.get("vgsbmout")) && checkUtil.isNotNullByObject(paramsNew.get("vgsbmin"))){
					ThrOperateCompanyApply outCompany = new ThrOperateCompanyApply().setVgsbm(paramsNew.get("vgsbmout").toString()).queryFirst();
					ThrOperateCompanyApply inCompany = new ThrOperateCompanyApply().setVgsbm(paramsNew.get("vgsbmin").toString()).queryFirst();
					if(!outCompany.getVgsSh().equals(inCompany.getVgsSh())){
						errMsgBySub += "第"+(i+1)+"行信息，不同公司实体无法划拨";
					}
				}

				paramsNew.put("pbid",tcwExpenseAllocationByManage.getBid());//单号
				paramsNewByItem.add(paramsNew);
			}
		}else {
			return R.error("详情信息为空！");
		}

		if (errMsgBySub != null && !"".equals(errMsgBySub)){
			return R.error(errMsgBySub);
		}
		hrMapper.deleteTcwExpenseAllocationByManageItemByBid(bid);
		for(Map<String, Object> item:paramsNewByItem){
			if(item.get("premark")!=null){
				item.put("remark",item.get("premark"));
			}
			TcwExpenseAllocationByManageItem tcwExpenseAllocationByManageItem = JSON.parseObject(JSON.toJSONString(item), TcwExpenseAllocationByManageItem.class);
			if(tcwExpenseAllocationByManageItem.getId()!=null && !"".equals(tcwExpenseAllocationByManageItem.getId())){
				//修改
				tcwExpenseAllocationByManageItemMapper.update(tcwExpenseAllocationByManageItem);
			}else {//新增
				tcwExpenseAllocationByManageItem.setStatus(1);

				tcwExpenseAllocationByManageItemMapper.insert(tcwExpenseAllocationByManageItem);
			}
		}
		return R.ok(AddDto.gotoEdit("/web/finance/tcwExpenseAllocationByManage/toEdit?bid=" + tcwExpenseAllocationByManage.getBid()));


	}




	@Override
	@Transactional
	public R deleteTrue(Long id) throws Exception {
		if (id == null) {
			return R.error("ID不能为空");
		}
		TcwExpenseAllocationByManage entity = new TcwExpenseAllocationByManage().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();

		if (!tsUserChange.getUserId().equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}

		// 删除主数据
		tcwExpenseAllocationByManageMapper.deleteTrue(id);

		// 删除子数据
		List<TcwExpenseAllocationByManageItem> listDetail = new TcwExpenseAllocationByManageItem().setPbid(entity.getBid()).queryList();
		for(TcwExpenseAllocationByManageItem detail : listDetail) {
			tcwExpenseAllocationByManageItemMapper.deleteTrue(detail.getId());
		}

		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}

	private String yzMsg(Map<String, Object> infoMap,long menuId){
		//验证导入字段
		String backMsg = "";
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		try {
			backMsg = checkUtil.checkTableColLengthAndDataType(
					"TCW_ExpenseAllocation_ByManage",
					listField,
					infoMap,
					ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1
			);
			if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
				return backMsg;
			}



		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	@Override
	@Transactional
	public R toDelByItem(Long id) throws Exception {

		TcwExpenseAllocationByManageItem tcwExpenseAllocationByManageItem = new TcwExpenseAllocationByManageItem();
		tcwExpenseAllocationByManageItem.setId(id);
		tcwExpenseAllocationByManageItem.setStatus(0);
		tcwExpenseAllocationByManageItemMapper.update(tcwExpenseAllocationByManageItem);
		return R.ok();
	}
	/**
	 * 流转通过
	 */
	@Override
	@Transactional
	public R flowPass(Long id, String loginUserId) throws Exception {

		TcwExpenseAllocationByManage entity = new TcwExpenseAllocationByManage().setId(id).queryFirst();

		TcwExpenseAllocationByManageItem entityItem = new TcwExpenseAllocationByManageItem().setPbid(entity.getBid()).queryFirst();

		if (entity == null) {
			return R.error("该申请单不存在,请核实后再操作!");
		}
		String bid = entity.getBid();
		YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();

		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else {
				// 若是制单流转，冻结账户
				if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
					//获取公司编码
					String vGsBm = entityItem.getVgsbmout();
					//获取要冻结的金额数
					BigDecimal amount = entityItem.getAmount();
					//冻结
					tcwAccountCountForCompanyService.frozen(vGsBm, amount,
							TcwOperateFrozenRunningEnum.DocumentType.TCW_ExpenseAllocationByManage.value,
							entityItem.getId(),
							entity.getBid(),
							null);
				}

				//若是制单完成
				if (f.getState() == Flow.State.FINISH.value) {
					flowFinish(bid);
				}

				return R.ok();
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("服务器正在开小差，请联系客服");
		}
	}



	@Override
	public R flowRefuse(Long id, String reason, String loginUserId) throws Exception {

		TcwExpenseAllocationByManage entity = new TcwExpenseAllocationByManage().setId(id).queryFirst();
		
		TcwExpenseAllocationByManageItem entityItem = new TcwExpenseAllocationByManageItem().setPbid(entity.getBid()).queryFirst();

		String bid = entity.getBid();

		R r = yspTaskService.flowRefuse(bid, reason, loginUserId);

		if (r.getCode() == R.Code.SUCCESS.value) {
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			// 若退回到制单状态，则解冻账户
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				//获取公司编码
				String vGsBm = entityItem.getVgsbmout();
				//获取要解冻的金额数
				BigDecimal amount = entityItem.getAmount();
				//解冻
				tcwAccountCountForCompanyService.thaw(vGsBm, amount,
						TcwOperateFrozenRunningEnum.DocumentType.TCW_ExpenseAllocationByManage.value,
						entityItem.getId(),
						entity.getBid(),
						null);
			}

		}
		return r;
	}


	@Override
	public R flowInit(Long id, String reason, String loginUserId) throws Exception {

		TcwExpenseAllocationByManage entity = new TcwExpenseAllocationByManage().setId(id).queryFirst();

		TcwExpenseAllocationByManageItem entityItem = new TcwExpenseAllocationByManageItem().setPbid(entity.getBid()).queryFirst();

		String bid = entity.getBid();

		R r = yspTaskService.flowInit(bid, reason, loginUserId);

		if (r.getCode() == R.Code.SUCCESS.value) {
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			// 若退回到制单状态，则解冻账户
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				//获取公司编码
				String vGsBm = entityItem.getVgsbmout();
				//获取要解冻的金额数
				BigDecimal amount = entityItem.getAmount();
				//解冻
				tcwAccountCountForCompanyService.thaw(vGsBm, amount,
						TcwOperateFrozenRunningEnum.DocumentType.TCW_ExpenseAllocationByManage.value,
						entityItem.getId(),
						entity.getBid(),
						null);
			}

		}
		return r;
	}


	/**
	 * 流转结束
	 */
	@Override
	@Transactional
	public void flowFinish(String bid) throws Exception {

		TcwExpenseAllocationByManage entity = new TcwExpenseAllocationByManage().setBid(bid).queryFirst();
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		Date theDate = new Date();
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		entity.setUpdateTime(theDate);
		/**
		 * 新增一条流水,去除触发器
		 * 必填：vgsbm划出公司编码；vgsjc划出公司简称；vgsbmp划入公司编码；vgsjcp划入公司简称；vjylx交易类型；fje交易金额；djysj交易时间；dshsj审核时间；vbz备注
		 * 选填：mname;mtype;mnid;mbid;mguid；writeTime记账时间（如果为空，默认审核时间）
		 */

		//获取详情信息
		List<TcwExpenseAllocationByManageItem> sonList = new TcwExpenseAllocationByManageItem().setPbid(entity.getBid()).queryList();
		for (TcwExpenseAllocationByManageItem sonItem : sonList){
			/*
			 * 新增流水
			 */
			tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
					sonItem.getVgsbmout(),sonItem.getVgsjcout(),sonItem.getVgsbmin(),sonItem.getVgsjcin(),sonItem.getBaseInfoType(),sonItem.getAmount().negate(),sonItem.getCreateTime(),theDate,
					"费用划拨管理单:"+entity.getBid()+",备注:"+(sonItem.getRemark()!=null?sonItem.getRemark():""),entity.getBid(),entity.getWriteTime());

			tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
					sonItem.getVgsbmin(),sonItem.getVgsjcin(),sonItem.getVgsbmout(),sonItem.getVgsjcout(),sonItem.getBaseInfoType(),sonItem.getAmount(),sonItem.getCreateTime(),theDate,
					"费用划拨管理单:"+entity.getBid()+",备注:"+(sonItem.getRemark()!=null?sonItem.getRemark():""),entity.getBid(),entity.getWriteTime());


		}
		TcwExpenseAllocationByManageItem entityItem = new TcwExpenseAllocationByManageItem().setPbid(entity.getBid()).queryFirst();

		//获取公司编码
		String vGsBm = entityItem.getVgsbmout();
		//获取要解冻的金额数
		BigDecimal amount = entityItem.getAmount();
		//解冻
		tcwAccountCountForCompanyService.thaw(vGsBm, amount,
				TcwOperateFrozenRunningEnum.DocumentType.TCW_ExpenseAllocationByManage.value,
				entityItem.getId(),
				entity.getBid(),
				null);
		//修改信息
		tcwExpenseAllocationByManageMapper.update(entity);



	}



	//批量导入
	@Override
	@Transactional
	public R importInfo(String rows,Long menuId){
		logger.info("导入的数据：\n"+rows);

		try {
			JSONArray detailList = JSON.parseArray(rows);
			String bid = "";
			for(int i=0;i<detailList.size();i++) {
				JSONObject info = detailList.getJSONObject(i);
				Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
				//验证导入字段

				//验证：划出运营公司编码
				if (checkUtil.isNullByObject(infoMap.get("vgsbmout"))) {
					return R.error("划出运营公司编码为空");
				}
				ThrOperateCompanyApply outCompany = new ThrOperateCompanyApply().setVgsbm(infoMap.get("vgsbmout").toString()).queryFirst();
				if(outCompany==null || outCompany.getId()==null){
					return R.error("划出运营公司编码有误");
				}

				//验证：划入运营公司编码
				if (checkUtil.isNullByObject(infoMap.get("vgsbmin"))) {
					return R.error("划入运营公司编码为空");
				}

				ThrOperateCompanyApply inCompany = new ThrOperateCompanyApply().setVgsbm(infoMap.get("vgsbmin").toString()).queryFirst();
				if(inCompany==null || inCompany.getId()==null){
					return R.error("划入运营公司编码有误");
				}

				//验证：交易类型
				if (checkUtil.isNullByObject(infoMap.get("baseInfoType"))) {
					return R.error("交易类型为空");
				}

				//验证：交易金额
				if (checkUtil.isNullByObject(infoMap.get("amount"))) {
					return R.error("交易金额为空");
				}
				if (!checkUtil.isDecimal(infoMap.get("amount").toString().trim(),"2")) {
					return R.error("交易金额应为2位小数");
				}

				//获取制单人信息
				TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
				if(tsUserChange ==null || tsUserChange.getId()==null){
					return R.error("未查询到制单人信息！");
				}

				TcwExpenseAllocationByManage entity = new TcwExpenseAllocationByManage();
				if ("".equals(bid)){
					if (checkUtil.isNullByObject(infoMap.get("bid"))) {
						bid = commonApiService.getCommonNextBid(menuId);
						entity.setBid(bid);
						entity.setCreateChangeId(tsUserChange.getId());
						entity.setStatus(0);
						entity.setEffectStock(FlowEnum.EffectStock.NOT_EFFECT.value);
						tcwExpenseAllocationByManageMapper.insert(entity);
					}else {
						bid = infoMap.get("bid").toString();
					}
				}

				TcwExpenseAllocationByManageItem itemInfo = new TcwExpenseAllocationByManageItem();
				itemInfo.setPbid(bid);
				itemInfo.setStatus(0);
				if (checkUtil.isNotNullByObject(infoMap.get("premark"))) itemInfo.setRemark(infoMap.get("premark").toString());
				itemInfo.setVgsbmin(inCompany.getVgsbm());
				itemInfo.setVgsjcin(inCompany.getVgsjc());
				itemInfo.setVgsbmout(outCompany.getVgsbm());
				itemInfo.setVgsjcout(outCompany.getVgsjc());
				itemInfo.setAmount(new BigDecimal(infoMap.get("amount").toString().trim()));
				itemInfo.setBaseInfoType(infoMap.get("baseInfoType").toString().trim());
				tcwExpenseAllocationByManageItemMapper.insert(itemInfo);

			}



			return R.ok(bid);
		}catch (Exception e){
			e.printStackTrace();
			return R.error("导入出错！");
		}



	}


	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String,Object> entity = new TcwExpenseAllocationByManage()

				.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
				.addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间
				.addLeftJoin("TB_CompanyInfo G ON G.vid=A.Vid")
				.addField("G.Vname vName")
				.addLeftJoin("(SELECT ISNULL(SUM(S.Amount),0) AS amount,S.Pbid FROM TCW_ExpenseAllocationByManageItem S GROUP BY S.Pbid) B ON B.Pbid = A.Bid")
				.addField("B.amount AS totalAmount")//付款总金额

				.setBid(bid)
				.queryFirstMap();

		return entity;
	}
	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList( String bid) throws Exception{
		List<Map<String, Object>> itemList = new TcwExpenseAllocationByManageItem()
				.addLeftJoin("THR_OperateCompanyApply B ON B.vgsbm=A.vgsbmout ")
				.addLeftJoin("THR_OperateCompanyApply C ON C.vgsbm=A.vgsbmin ")
				.addLeftJoin("TB_StaticConfig D ON D.Lev=B.OperationsAttribute AND D.KeyTwo = 'OperateCompanyApply-OperationsAttribute' ")
				.addField("D.Name operationsAttributeout")

				.addLeftJoin("TB_StaticConfig E ON E.Lev=C.OperationsAttribute AND E.KeyTwo = 'OperateCompanyApply-OperationsAttribute' ")
				.addField("E.Name operationsAttributein")

				/*
				.addField("CASE " +
						"WHEN B.OperationsAttribute=2 THEN '运营账户' " +
						" ELSE '非运营账户' END operationsAttributeout")
				.addField("CASE " +
						"WHEN C.OperationsAttribute=2 THEN '运营账户' " +
						" ELSE '非运营账户' END operationsAttributein")

				 */
				.addField("A.remark premark")
				.setPbid(bid)
				.queryMap();
		return itemList;
	}


}
